package ink.xiaobaibai.handler;

import ink.xiaobaibai.token.MyUsernamePasswordAuthenticationToken;
import ink.xiaobaibai.units.JWTUnit;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 账号密码登录成功处理器
 * @author: 小白白
 * @create: 2021-05-14
 **/

public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功,放个jwt放到请求头
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        List<String> roleList = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        String jwt = JWTUnit.getJWT(((MyUsernamePasswordAuthenticationToken) authentication).getUserId(), authentication.getCredentials().toString(), roleList);
        response.setHeader("Authorization", jwt);
    }

}
